/* -------------------------- Simple Form ------------------------- */
/**
 * @param props
 * 		props.formURL:	{String}	The URL for form submitting
 * 		props.formData:	{String[]}	The visiable subjects. It's avariable only when 'dataStruct' exist.
 * 		props.onSubmitSucc:	{Function}	The function will run while the form be submitted successfully.
 * 
 * @tag	{TABLE}	<css>AWF_Form</css>
 * 
 * @author HongYu
 */
function AWFForm(props) {
	this.props = props || {};
	this.formURL = this.props.formURL;
	this.target = this.props.formTarget || "";
	this.formData = this.props.formData;
}

AWFForm.prototype.doSubmit = function(requestID, responseID) {
	var self = this;
	var detail = ToJSONString(this.formData,1,1);
	var data = {
		target: this.target,
		detail: detail
	};
	var header = $('.demo-header').text();
	$('#data-cache').data(header + '\.request', __SERVICE_URL_PREFIX__ + this.formURL + "\n" + ToJSONString(data,1,0));
	$("#" + header + "\\.request")
		.empty()
		.append("<pre>" + $('#data-cache').data(header + '\.request') + "</pre>")
		.show();

	if (this.formURL) {
		AWF.showWaiting();
		if ($.browser.mozilla) {
			netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
			netscape.security.PrivilegeManager.enablePrivilege("UniversalFileRead");
		}

		$.ajax({
			type: "POST",
			url: __SERVICE_URL_PREFIX__ + this.formURL, 
			data: data, 
			error: function(xhr, error) {
				_R();
				$("#" + header + "\\.response")
					.empty()
					.append(xhr.responseText)
					.show();
				alert(error);
			},
			success: function(data) {
				_R();
				if (data == null || data == "") {
					alert("web service not avariable!");
				} else {
					if (typeof data == "string")
						data = richEval(data);
					$('#data-cache').data(header + '\.response', ToJSONString(data,1,0));
					$("#" + header + "\\.response")
						.empty()
						.append("<pre>" + $('#data-cache').data(header + '\.response') + "</pre>")
						.show();
					//$("#tabs").tabs("select", 1);
					try {
						self.doPostStage(data);
					}
					catch (e) {
						alert("Error: " + e);
					}
				}
			}
		});

	}else {
		alert("Error: Miss formURL.");
	}
}
AWFForm.prototype.doValidateAll = function() {
	return true;
}

AWFForm.prototype.doPostStage = function(v) {
	try	{
		if (this.props.onSubmitSucc)
			this.props.onSubmitSucc(v);
	}
	catch (e) {
		alert("Error: " + e);
	}
}

AWFForm.prototype.__submitComplete = function(formData, responseID, waiting, url, parameters, req) {
	var s = req.responseText;
	var v = richEval(s);

	SetValueByID(responseID, ToJSONString(v));
	BlockSet(responseID, 1);

	try	{
		if (this.props.onSubmitSucc)
			this.props.onSubmitSucc(v);
	}
	catch (e) {
		alert("Error: " + e);
	}
	_R(waiting);
}

function ParseXMLString(xmlStr) {
	var xmlDoc = new ActiveXObject("Msxml2.DOMDocument.3.0");
	xmlDoc.async = false;
	try	{
		xmlDoc.loadXML(xmlStr);
		var result = xmlDoc.selectSingleNode("//string");
		if (result.text.length > 0) {
			return result.text
		} else {
			return "NULL"
		}
	}
	catch (ex) {
		alert(xmlStr);
	}
	return "";
}

richEval = function(s) {
	if (s.length == 0) {
		return {res: 0, error: {code: 201, message: "Web Server is not available"}, data: {}};
	}
	try {
		//var ts = ParseXMLString(s);
		//DEBUG(ts);
		//alert(s);
		var rv = eval('('  + s + ')');
		
		return rv;
	}catch(e) {
		return {res: 0, error: e, data: {}};
	}
}
/*
richEval = function(ts) {
	try	{
		var rv = eval('('  + ts + ')');
		return rv;
	}
	catch (e) {
		alert(e);
	}
}*/

ToJSONString = function(props,bFormatted,lTabs) {
	var sAddon = "";
	var sTab = "";
	var bFormattedJSON = true;
	var lTabSize = 4;
	
	if (bFormattedJSON) {
		if (!bFormatted) {
			bFormatted = 1;
			lTabs = 0;
		}
		
		for (var i=0; i<lTabSize; i++)
			sTab += " ";
		
		sAddon += "\n";
		for (var i=0; i<lTabs; i++)
			sAddon += sTab;
	}
	else {
		bFormatted = 0;
		lTabs = 0;
	}
	
		if (props instanceof Array) {
			var str = "[";
			var count = 0;
			for (var i=0; i<props.length; i++) {
				if (count++ > 0) str+=",";
				switch (typeof props[i]) {
					case "object" :
						str+=sAddon+sTab+ToJSONString(props[i],bFormatted,lTabs+1);
						break;
					default :
						str+=sAddon+sTab+"\""+props[i]+"\"";
						break;
				}
			}
			str+=((count)?sAddon:"")+"]";
			return str;
		}

		var props = props || {};
		var str = "{";
		var count = 0;
		for (var k in props) {
			if (count++ > 0) str+=",";
			switch (typeof props[k]) {
				case "object" :
					str+=sAddon+sTab+"\""+k+"\""+":"+ToJSONString(props[k],bFormatted,lTabs+1);
					break;
				default :
					str+=sAddon+sTab+"\""+k +"\""+":\""+props[k]+"\"";
					break;
			}
		}
		str+=((count)?sAddon:"")+"}";
		return str;
}

function getSelectedListValueByIndex(index){
	  var selectKeys=new Array();
      var selectValues=new Array();

	  var bSelect=document.getElementsByTagName("SELECT");
	  //alert(bSelect[0][bSelect[0].selectedIndex].innerHTML);
	  return bSelect[index].value;
	
	//return 0;
}

function getSelectedListValueById(id){

	  var bSelect=document.getElementById(id);
	  //alert(bSelect[0][bSelect[0].selectedIndex].innerHTML);
	  return bSelect.value;
	
	//return 0;
}
function getSelectedRadioValue(buttonGroup){
	for (var i = 0; i < buttonGroup.length; i++) {
		if (buttonGroup[i].checked) {
			return buttonGroup[i].value;
		}
	}
	return 0;
}

/* AWF Waiting */
if (typeof AWF == "undefined")
	AWF = {};

AWF.showWaiting = function(){
	var scrollTop = Math.max(document.documentElement.scrollTop, document.body.scrollTop);
	var scrollLeft = Math.max(document.documentElement.scrollLeft, document.body.scrollLeft);
	var x = parseInt((document.body.clientWidth - 10) / 2) + scrollLeft;
	var y = parseInt((document.body.clientHeight - 10)/ 2) + scrollTop;
	return $("<div>", {
				"class": "awf-waiting"
			})
			.appendTo("body")
			.attr({"style": "top: " + y + "px; left: " + x + "px; z-index: 1000"});
}

_R = function() {
	$('div').remove('.awf-waiting');
}

